import type { DyOrderInfo, WechatDramaOrder, WxPaymentDTO } from '@/api/pay';
import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
import { userActionLog } from '@/api/datapoint';
import { useAppStore } from '@/pinia/app';
export type TtOrderPayResult = tt.GetOrderPaymentSuccess & {
  /** 订单号 */
  outTradeNo: string;
};

/** web支付 */
export function webPay(fromDom: string) {
  const div = document.createElement('formdiv');
  div.innerHTML = fromDom;
  document.body.appendChild(div);
  const from = div.querySelector('form');
  from?.submit();
  div.remove();
}

/** 快手支付 */
export function ksPay(orderInfo: ks.OderInfo): Promise<boolean> {
  return new Promise((resolve, reject) => {
    const sys = mxpGetSysInfoStore().getSysInfo();
    const devicePlatform = sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform;
    ks.pay({
      serviceId: '1',
      orderInfo,
      payType: devicePlatform === 'ios' ? 'IAPPurchase' : undefined,
      success() {
        resolve(true);
      },
      fail(error: unknown) {
        reject(error);
      },
    });
  });
}

/** 微信普通支付 */
export function wxOrderPay(dto: WxPaymentDTO): Promise<boolean> {
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      timeStamp: dto.timestamp,
      nonceStr: dto.nonceStr,
      package: dto.packageVal,
      signType: dto.signType,
      paySign: dto.paySign,
      success() {
        resolve(true);
      },
      fail(error) {
        userActionLog({
          userId: useAppStore().userInfo?.userId,
          data: JSON.stringify(dto),
          eventType: 'WX_ORDERPAY',
          msg: JSON.stringify(error),
        });
        console.log('唤起支付失败====', error);
        reject(error);
      },
    });
  });
}

/** 微信虚拟支付 */
export function wxOrderVirtualPay(orderInfo: WechatDramaOrder): Promise<boolean> {
  return new Promise((resolve, reject) => {
    wx.requestVirtualPayment({
      signData: orderInfo.signData,
      mode: 'short_series_coin',
      paySig: orderInfo.paySig,
      signature: orderInfo.signature,
      success() {
        resolve(true);
      },
      fail(error) {
        userActionLog({
          userId: useAppStore().userInfo?.userId,
          data: JSON.stringify(orderInfo),
          eventType: 'WX_ORDER_VIRTUAL_PAY',
          msg: JSON.stringify(error),
        });
        console.log('唤起支付失败====', error);
        reject(error);
      },
    });
  });
}

/** 头条统一支付 */
export function ttOrderPay(orderInfo: DyOrderInfo): Promise<TtOrderPayResult> {
  return new Promise((resolve, reject) => {
    tt.requestOrder({
      data: orderInfo.skuOrderRespDTO,
      byteAuthorization: orderInfo.byteAuthorization,
      success(res1) {
        tt.getOrderPayment({
          orderId: res1.orderId,
          success(res2) {
            resolve({ ...res2, outTradeNo: orderInfo.outTradeNo });
          },
          fail(error) {
            if (String(error.errNo) === String(9) && 'orderId' in error) {
              resolve({ ...error, orderId: String(error.orderId), outTradeNo: orderInfo.outTradeNo });
            } else {
              userActionLog({
                userId: useAppStore().userInfo?.userId,
                data: JSON.stringify(orderInfo),
                eventType: 'TOUTIAO_ORDER_PAY',
                msg: JSON.stringify(error),
              });
              console.log('支付失败====', error);
              reject(error);
            }
          },
        });
      },
      fail(error) {
        console.log('唤起支付失败====', error);
        reject(error);
      },
    });
  });
}

/** 头条担保支付 */
export function ttPay(orderInfo: tt.OderInfo): Promise<boolean> {
  return new Promise((resolve, reject) => {
    tt.pay({
      service: 5,
      _debug: import.meta.env.DEV ? 1 : 0,
      orderInfo,
      success() {
        resolve(true);
      },
      fail(error: unknown) {
        userActionLog({
          userId: useAppStore().userInfo?.userId,
          data: JSON.stringify(orderInfo),
          eventType: 'TOUTIAO_PAY',
          msg: JSON.stringify(error),
        });
        reject(error);
      },
    });
  });
}
